package com.oxy.svc.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.TransactionStatus;

import com.oxy.action.util.ActionUtil;
import com.oxy.common.constant.ActionConstant;
import com.oxy.model.Pager;
import com.oxy.model.bo.CurrUserInfoBO;
import com.oxy.model.dao.MemberDao;
import com.oxy.model.po.MemberPO;
import com.oxy.svc.MemberSvc;
import com.oxy.util.Oxy;
import com.oxy.util.SysErrException;

public class MemberSvcImpl extends BaseSvc implements MemberSvc{
	private final static Log logger = Oxy.getLogManager().getLogCommon();

	public long getMemberCount() {
		long ret = 0;
		MemberDao dao = (MemberDao)this.getDaoHolder().getDaoByIfClass(MemberDao.class);
		ret = dao.count();
		return ret;
	}
	
	public List<MemberPO> list(Pager pager) {
		List<MemberPO> retList = new ArrayList<MemberPO>();
		List<MemberPO> poList = null;
		MemberDao dao = (MemberDao)this.getDaoHolder().getDaoByIfClass(MemberDao.class);
		poList = dao.list(pager);
		retList = poList;
		return retList;
	}

	public long regMember(MemberPO mem) throws SysErrException {
		long uid = 0l;
		//TransactionStatus tx = this.startTransaction();
		
		try {
			MemberDao dao = (MemberDao)this.getDaoHolder().getDaoByIfClass(MemberDao.class);
			if(mem.getUid() == null) {
				mem.setUid(new Long(0));
			}
			if(mem.getGid() == null) {
				mem.setGid(new Integer(1));
			}
			mem.setStatus(new Boolean(true));
			mem.setRegdate(new Date());
			int ret = dao.insertMember(mem);
			if(ret == 1) {
				uid = mem.getUid().longValue();
				//this.commit(tx);
			}
			else {
				//this.rollback(tx);
			}
		} 
		catch (DataAccessException e) {
			//this.rollback(tx);
			//logger.info(e.getMessage());
			throw e;
		}
		
		return uid;
	}

	public boolean loginByEmail(String email, String password) {
		boolean ret = false;
		TransactionStatus tx = this.startTransaction();
		
		try {
			MemberDao dao = (MemberDao)this.getDaoHolder().getDaoByIfClass(MemberDao.class);
			ret = dao.loginByEmail(email, password);
			
			if(ret == true) {
				CurrUserInfoBO user = (CurrUserInfoBO)ActionUtil.getSessionAttr(ActionConstant.SESSION.CURR_USER_INFO);
				if(user != null) {
					ActionUtil.rmSessionAttr(ActionConstant.SESSION.CURR_USER_INFO);
				}
				
				user = new CurrUserInfoBO();
				user.setEmail(email);
				ActionUtil.setSessionAttr(ActionConstant.SESSION.CURR_USER_INFO, user);
				
				this.commit(tx);
			}
			else {
				this.rollback(tx);
			}
		} catch(DataAccessException e) {
			//this.rollback(tx);
			//logger.info(e.getMessage());
			throw e;
		}
		return ret;
	}
}

